'use strict';

const fs = require('fs');
const path = require('path');
const Controller = require('egg').Controller;
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');

class FileController extends Controller {
  async upload() {
    const stream = await this.ctx.getFileStream();
    const origin = stream.filename
    console.log(origin)
    const date = new Date();
    const filename = date.getTime() + path.extname(stream.filename).toLowerCase();
    const appdir = path.join('app/public/', date.toLocaleDateString());
    const pathdir = path.join(this.config.baseDir, appdir);
    if(!fs.existsSync(pathdir)) {
      fs.mkdir(pathdir);
    }
    const target = path.join(pathdir, filename);
    const writeStream = fs.createWriteStream(target);
    try {
      await awaitWriteStream(stream.pipe(writeStream));
      const insertId = await this.ctx.service.file.create({filename: origin, path: appdir, name: filename})
      this.ctx.body = { data: { id: insertId } };
    } catch (err) {
      await sendToWormhole(stream);
      throw err;
    }

  }

  async download() {
    const id = this.ctx.params.id;
    const file = await this.ctx.service.file.find(id);
    const filePath = path.join(this.config.baseDir, file.path, file.name);
    this.ctx.attachment(file.filename);
    this.ctx.set('Content-Type', 'application/octet-stream');
    this.ctx.body = fs.createReadStream(filePath);
  }
}

module.exports = FileController;
